package udp;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class MyClient {

    public static void main(String[] args) {
        String msg = "接收完毕!";

        try {
            InetAddress serverIp; //服务器端的ip地址
            int serverPort; //服务器的端口
            //1.创建客户端的DatagramSocket
            DatagramSocket client_ds = new DatagramSocket(6666);
            //2.创建用字节数组
            byte[] buff = new byte[1024];
            //3.创建接收的数据包
            DatagramPacket dp = new DatagramPacket(buff, buff.length);
            //4.接收
            client_ds.receive(dp);
            //打印接收的消息以及相关的数据包的信息
            //System.out.println(new String(dp.getData())+"From:"+dp.getAddress()+"port:"+dp.getPort()+"To:"+dp.getSocketAddress()+"length:"+dp.getLength()+"字节");
            System.out.println("接收的消息是：");
            System.out.println(new String(dp.getData(), 0, dp.getLength()));
            System.out.println(new String(" From:" + dp.getAddress() + " port:" + dp.getPort() + " length:" + dp.getLength() + "字节"));

            //5.给服务器发送消息
            serverIp = dp.getAddress();
            serverPort = dp.getPort();
            DatagramPacket clientDataPacket = new DatagramPacket(msg.getBytes(), msg.getBytes().length, serverIp, serverPort);
            client_ds.send(clientDataPacket);
            System.out.println("客户端回复成功");

            //6.关闭
            client_ds.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
